import { ref } from 'vue'
import { useMessageStore } from '@/stores/messageStore'
import { storeToRefs } from 'pinia'
import { useModalStore } from '@/stores/modalStore'
import { useMainIndexStore } from '@/stores/mainIndexStore'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import { useCurrActStroe } from '@/stores/currActStore'
import { useSocketStore } from '@/stores/socketStore'
import type { ErrorData, UserList } from '@/types/loginType'
export default function () {
  const { changeData } = useModalStore()
  const userList = ref<UserList[]>([])
  // 消息计数
  const { msgItems } = storeToRefs(useSocketStore())
  // 获取 user 通讯列表
  async function getUserList() {
    const { getMessageUserList } = useAsyncAxios()
    const { currUser } = storeToRefs(useCurrActStroe())
    const { status, data } = await getMessageUserList(currUser.value.id)
    if (status === 200) {
      const result = data as UserList[]
      console.log(result)

      if (result.length > 0) {
        userList.value = result as UserList[]
        const item = userList.value[0]
        userClicked({ id: item.id, name: item.name, img: item.img })
        result.forEach((log) => {
          msgItems.value[log.id] = log.total
        })
      }
    } else {
      changeData({ status, data: data as ErrorData })
    }
  }

  const hasNewMsg = ref(false)

  const isSelected = ref('')

  async function userClicked(user: { id: string; name: string; img: string }) {
    const { assignTitle } = useMainIndexStore()
    assignTitle({ msg: user.name, img: user.img })
    const { getLogsData, changeUserTarget } = useMessageStore()
    changeUserTarget(user)
    isSelected.value = user.id
    // 传值
    getLogsData(user.id)
  }

  return { hasNewMsg, userList, isSelected, userClicked, getUserList, msgItems }
}
